﻿#include "CodeEditor.h"
#include <QPainter>
#include <QTextBlock>
#include "Defs.h"
#include <QMenu>
#include "SuspendedSearchBox.h"
#include "SearchService.h"
#include "QMessageBox"
#include "ConfigManager.h"

CodeEditor::CodeEditor(QWidget* parent) : QPlainTextEdit(parent)
{
    m_lineNumberArea = new LineNumberArea(this);

    // 禁用自动换行，启用横向滚动条
    setLineWrapMode(QPlainTextEdit::NoWrap);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);

    connect(this, &CodeEditor::blockCountChanged, this, &CodeEditor::updateLineNumberAreaWidth);
    connect(this, &CodeEditor::updateRequest, this, &CodeEditor::updateLineNumberArea);
    connect(this, &CodeEditor::cursorPositionChanged, this, &CodeEditor::highlightCurrentLine);
	// 连接文本改变信号，用于更新字数统计
	connect(this, &CodeEditor::textChanged, this, &CodeEditor::onTextChanged);
    // 新增：连接文本选择变化信号，触发全文档高亮
    connect(this, &CodeEditor::selectionChanged, this, &CodeEditor::onSelectionChanged);

	emit currentWordNumberChanged(0);// 初始化字数统计
    emit currentLineNumberChanged(1);  // 初始化行数统计（空文档也有1行）

    updateLineNumberAreaWidth(0);
    highlightCurrentLine();

    // 加载保存的字体设置
    loadFontSettings();

    zoomIn(3);//初始视图大小

    setScrollBarStyle();

	connect(&ThemeManager::GetInstance(), &ThemeManager::themeChanged, this, &CodeEditor::onThemeChanged);

    // ===== 关键修复：手动应用当前主题 =====
    // 因为 ThemeManager 在构造时已经发射过 themeChanged 信号
    // 但那时 CodeEditor 还没连接，所以需要手动应用一次
    ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();
    if (currentTheme == ThemeManager::Theme::Dark) {
        setDarkTheme();
    }
    else {
        setLightTheme();
    }
}

int CodeEditor::lineNumberAreaWidth()
{
    int digits = 1;
    int max = qMax(1, blockCount());
    while (max >= 10) {
        max /= 10;
        ++digits;
    }
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
		int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits;
#else
	int space = 3 + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits;
#endif

    return space;
}

void CodeEditor::setEncodingType(const TextFileUtils::Encoding& encodingType, bool needConvert)
{
	// 无需重复设置相同的编码格式
    if(encodingType == m_currentEncodingType) {
        return;
	}
    else {
        if (needConvert) {
            // 转换现有文本到新的编码格式
            QString currentText = toPlainText();
            // 根据编码格式进行相应处理
            switch (m_currentEncodingType)
            {
            case TextFileUtils::UTF8:
            
                break;
            case TextFileUtils::GBK:
                break;
            case TextFileUtils::GB2312:
                break;
            case TextFileUtils::BIG5:
                break;
            case TextFileUtils::ASCII:
                break;
            case TextFileUtils::UTF16LE:
                break;
            case TextFileUtils::UTF16BE:
                break;
            case TextFileUtils::AUTO_DETECT:
                break;
            default:
                break;
            }
        }

		m_currentEncodingType = encodingType;// 更新当前编码格式
    }
}

void CodeEditor::setText(const QString& text, const TextFileUtils::Encoding& encodingType)
{
	setEncodingType(encodingType, false);// 传入的文本已经是指定编码格式，无需转换
	QPlainTextEdit::clear();// 清空当前文本
	QPlainTextEdit::setPlainText(text);
}

bool CodeEditor::scrollToLine(int lineNumber, bool centerLine)
{
    // 行号从1开始，需要转换为从0开始的索引
    int blockNumber = lineNumber - 1;

    // 检查行号是否有效
    if (blockNumber < 0 || blockNumber >= blockCount()) {
        return false;
    }

    // 获取指定行的文本块
    QTextBlock block = document()->findBlockByNumber(blockNumber);
    if (!block.isValid()) {
        return false;
    }

    // 创建光标并移动到该行
    QTextCursor cursor(block);
    setTextCursor(cursor);

    // 根据参数决定是居中显示还是仅确保可见
    if (centerLine) {
        centerCursor();  // 将光标所在行居中显示
    }
    else {
        ensureCursorVisible();  // 确保光标可见（滚动最小距离）
    }
	return true;
}

bool CodeEditor::gotoLine(int lineNumber, bool selectLine)
{
	// 如果行数小于1或者行数大于总行数，则不进行任何操作
    if(lineNumber < 1 || lineNumber > blockCount()) {
        return false;
	}
    // 行号从1开始，需要转换为从0开始的索引
    int blockNumber = lineNumber - 1;

    // 检查行号是否有效
    if (blockNumber < 0 || blockNumber >= blockCount()) {
        return false;
    }

    // 获取指定行的文本块
    QTextBlock block = document()->findBlockByNumber(blockNumber);
    if (!block.isValid()) {
        return false;
    }

    // 创建光标并移动到该行开始位置
    QTextCursor cursor(block);

    // 如果需要选中整行
    if (selectLine) {
        cursor.movePosition(QTextCursor::StartOfBlock);
        cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
    }
    else {
        // 否则只是将光标移动到行首
        cursor.movePosition(QTextCursor::StartOfBlock);
    }

    setTextCursor(cursor);
    centerCursor();  // 居中显示
    setFocus();  // 设置焦点到编辑器

	return true;
}

void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */)
{
    setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
}

void CodeEditor::updateLineNumberArea(const QRect& rect, int dy)
{
    if (dy)
        m_lineNumberArea->scroll(0, dy);
    else
        m_lineNumberArea->update(0, rect.y(), m_lineNumberArea->width(), rect.height());

    if (rect.contains(viewport()->rect()))
        updateLineNumberAreaWidth(0);
}

void CodeEditor::onTextChanged()
{
    // 计算当前总字数（字符数）
    int wordCount = toPlainText().length();
    // 计算当前总行数
    int lineCount = blockCount();

    qDebug() << "Current word count:" << wordCount;
    qDebug() << "Current line count:" << lineCount;

    // 发射信号通知字数变化
    emit currentWordNumberChanged(wordCount);
    // 发射信号通知行数变化
    emit currentLineNumberChanged(lineCount);
}

void CodeEditor::onSelectionChanged()
{
    QList<QTextEdit::ExtraSelection> allSelections;

    // 根据当前主题获取颜色
    ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();

    QColor currentLineColor;
    QColor matchHighlightColor;

    if (currentTheme == ThemeManager::Theme::Dark) {
        // 深色主题颜色
        currentLineColor = QColor(76, 80, 92);      // 深蓝色调
        matchHighlightColor = QColor(63, 81, 181);  // 深色主题的匹配高亮颜色（深蓝色）
    }
    else {
        // 浅色主题颜色
        currentLineColor = QColor(Qt::yellow).lighter(160); // 浅黄色
        matchHighlightColor = QColor(Qt::blue).lighter(180); // 浅蓝色
    }

    // 1. 保留原有"当前行高亮"功能
    if (!isReadOnly())
    {
        QTextEdit::ExtraSelection currentLineSel;
        currentLineSel.format.setBackground(currentLineColor);
        currentLineSel.format.setProperty(QTextFormat::FullWidthSelection, true);
        currentLineSel.cursor = textCursor();
        currentLineSel.cursor.clearSelection(); // 清除光标选择，避免影响行高亮
        allSelections.append(currentLineSel);
    }

    // 2. 处理"全文档匹配高亮"（仅当存在有效选中文本时）
    QString selectedText = textCursor().selectedText();
    if (!selectedText.isEmpty())
    {
        // 获取所有匹配子串的位置
        QList<QPair<int, int>> matches = findAllMatches(selectedText);

        // 为每个匹配子串创建高亮项
        foreach(auto& match, matches)
        {
            QTextEdit::ExtraSelection matchSel;
            matchSel.format.setBackground(matchHighlightColor);

            // 根据主题设置文字颜色，确保可读性
            if (currentTheme == ThemeManager::Theme::Dark) {
                matchSel.format.setForeground(QColor(255, 255, 255)); // 深色主题用白色文字
            }
            else {
                matchSel.format.setForeground(QColor(0, 0, 0)); // 浅色主题用黑色文字
            }

            // 设置光标到匹配位置，并选中匹配文本
            QTextCursor matchCursor = document()->rootFrame()->firstCursorPosition();
            matchCursor.setPosition(match.first); // 移动到起始索引
            matchCursor.setPosition(match.first + match.second, QTextCursor::KeepAnchor); // 选中匹配长度
            matchSel.cursor = matchCursor;
            allSelections.append(matchSel);
        }
    }

    // 3. 应用所有高亮（覆盖原有高亮，合并两种效果）
    setExtraSelections(allSelections);
}

void CodeEditor::onSwitchFontTriggered()
{
    if (!m_fontSwitch) {
        m_fontSwitch = new FontScrollWidget(nullptr);
        connect(m_fontSwitch, &FontScrollWidget::fontChanged, this, &CodeEditor::onFontChanged);
    }
    m_fontSwitch->show();
    m_fontSwitch->scrollToFont(this->font());// 滚动到当前字体增强体验
}

void CodeEditor::onFontChanged(const QFont& font)
{
    qDebug() << "切换字体为:" << font.family();

    // 保存当前字号和其他属性，只改变字体家族
    QFont newFont = font;
    QFont currentFont = this->font();
    newFont.setPointSize(currentFont.pointSize());
    newFont.setBold(currentFont.bold());
    newFont.setItalic(currentFont.italic());

    this->setFont(newFont);

    // 修复：字体改变后更新行号区域
    updateLineNumberAreaWidth(0);
    m_lineNumberArea->update();

    // 保存到配置文件
    saveFontSettings(newFont);
}

void CodeEditor::onThemeChanged(ThemeManager::Theme newTheme)
{
    if (newTheme == ThemeManager::Theme::Dark) {
		//文字浅色，背景深色
        setDarkTheme();
    }
    else {
		//文字深色，背景浅色
        setLightTheme();
    }
}

void CodeEditor::setScrollBarStyle()
{
    // 设置垂直滚动条样式
    verticalScrollBar()->setStyleSheet(R"(
        QScrollBar:vertical {
            background: transparent;
            width: 12px;
            margin: 0px;
            border-radius: 6px;
        }
        QScrollBar:vertical:hover {
            background: transparent;
        }
        QScrollBar::handle:vertical {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                stop:0 #F1F1F1, stop:1 #F1F1F1);
            border: 2px solid transparent;
            border-radius: 5px;
            min-height: 20px;
        }
        QScrollBar::handle:vertical:hover {
            background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                stop:0 #F1F1F1, stop:1 #F2F6FD);
            border: 2px solid #F1F1F1;
        }
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
            border: none;
            background: none;
        }
        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
            background: none;
        }
    )");

    // 设置水平滚动条样式
    horizontalScrollBar()->setStyleSheet(R"(
        QScrollBar:horizontal {
            background: transparent;
            height: 12px;
            margin: 0px;
            border-radius: 6px;
        }
        QScrollBar:horizontal:hover {
            background: transparent;
        }
        QScrollBar::handle:horizontal {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #F1F1F1, stop:1 #F1F1F1);
            border: 2px solid transparent;
            border-radius: 5px;
            min-width: 20px;
        }
        QScrollBar::handle:horizontal:hover {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                stop:0 #F1F1F1, stop:1 #F2F6FD);
            border: 2px solid #F1F1F1;
        }
        QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {
            border: none;
            background: none;
        }
        QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {
            background: none;
        }
    )");
}

QList<QPair<int, int>> CodeEditor::findAllMatches(const QString& targetText)
{
    QList<QPair<int, int>> matches;
    if (targetText.isEmpty()) return matches; // 空文本直接返回

    // 获取全文档纯文本
    QString fullText = toPlainText();
    int textLength = targetText.length();
    int fullLength = fullText.length();

    // 遍历全文档，查找所有匹配（敏感匹配）
    int pos = 0;
    while (pos <= fullLength - textLength)
    {
        pos = fullText.indexOf(targetText, pos, Qt::CaseSensitive);
        if (pos == -1) break; // 无更多匹配，退出循环

        // 记录匹配的起始索引和长度
        matches.append(qMakePair(pos, textLength));
        pos += textLength; // 移动到下一个可能匹配的位置（避免重叠匹配）
    }

    return matches;
}

void CodeEditor::saveFontSettings(const QFont& font)
{
    ConfigManager::instance().setEditorFont(font);
    qDebug() << "保存字体设置:" << font.family() << "大小:" << font.pointSize();
}

void CodeEditor::setDarkTheme()
{
    // 设置编辑器基础样式
    setStyleSheet(R"(
        QPlainTextEdit {
            background-color: #1E1E1E;
            color: #E8E8E8;
            border: 1px solid #3E3E42;
            border-radius: 8px;
            padding: 8px;
            selection-background-color: #264F78;
        }
    )");

    // 设置行号区域深色主题
    setLineNumberAreaDarkTheme();

    // 设置滚动条深色主题
    setScrollBarDarkTheme();

    // 更新当前行高亮颜色
    highlightCurrentLine();

    qDebug() << "CodeEditor 已应用深色主题";
}

void CodeEditor::setLightTheme()
{
    // 设置编辑器基础样式
    setStyleSheet(R"(
        QPlainTextEdit {
            background-color: #FFFFFF;
            color: #24292E;
            border: 1px solid #E1E4E8;
            border-radius: 8px;
            padding: 8px;
            selection-background-color: #B5D5FF;
        }
    )");

    // 设置行号区域浅色主题
    setLineNumberAreaLightTheme();

    // 设置滚动条浅色主题
    setScrollBarLightTheme();

    // 更新当前行高亮颜色
    highlightCurrentLine();

    qDebug() << "CodeEditor 已应用浅色主题";
}

void CodeEditor::setLineNumberAreaDarkTheme()
{
    // 行号区域在paintEvent中处理，这里确保样式正确
    if (m_lineNumberArea) {
        m_lineNumberArea->update();
    }
}

void CodeEditor::setLineNumberAreaLightTheme()
{
    // 行号区域在paintEvent中处理，这里确保样式正确
    if (m_lineNumberArea) {
        m_lineNumberArea->update();
    }
}

void CodeEditor::setScrollBarDarkTheme()
{
    // 设置垂直滚动条深色样式
    verticalScrollBar()->setStyleSheet(R"(
        QScrollBar:vertical {
            background: #2D2D30;
            width: 12px;
            margin: 0px;
            border-radius: 6px;
            border: 1px solid #3E3E42;
        }
        QScrollBar:vertical:hover {
            background: #3C3C3C;
        }
        QScrollBar::handle:vertical {
            background: #5A5A5A;
            border: 2px solid transparent;
            border-radius: 5px;
            min-height: 20px;
        }
        QScrollBar::handle:vertical:hover {
            background: #6B6B6B;
            border: 2px solid #5A5A5A;
        }
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
            border: none;
            background: none;
            height: 0px;
        }
        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
            background: none;
        }
    )");

    // 设置水平滚动条深色样式
    horizontalScrollBar()->setStyleSheet(R"(
        QScrollBar:horizontal {
            background: #2D2D30;
            height: 12px;
            margin: 0px;
            border-radius: 6px;
            border: 1px solid #3E3E42;
        }
        QScrollBar:horizontal:hover {
            background: #3C3C3C;
        }
        QScrollBar::handle:horizontal {
            background: #5A5A5A;
            border: 2px solid transparent;
            border-radius: 5px;
            min-width: 20px;
        }
        QScrollBar::handle:horizontal:hover {
            background: #6B6B6B;
            border: 2px solid #5A5A5A;
        }
        QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {
            border: none;
            background: none;
            width: 0px;
        }
        QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {
            background: none;
        }
    )");
}

void CodeEditor::setScrollBarLightTheme()
{
    // 设置垂直滚动条浅色样式
    verticalScrollBar()->setStyleSheet(R"(
        QScrollBar:vertical {
            background: #F8F9FA;
            width: 12px;
            margin: 0px;
            border-radius: 6px;
            border: 1px solid #E1E4E8;
        }
        QScrollBar:vertical:hover {
            background: #F1F2F4;
        }
        QScrollBar::handle:vertical {
            background: #D1D5DB;
            border: 2px solid transparent;
            border-radius: 5px;
            min-height: 20px;
        }
        QScrollBar::handle:vertical:hover {
            background: #9CA3AF;
            border: 2px solid #D1D5DB;
        }
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
            border: none;
            background: none;
            height: 0px;
        }
        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
            background: none;
        }
    )");

    // 设置水平滚动条浅色样式
    horizontalScrollBar()->setStyleSheet(R"(
        QScrollBar:horizontal {
            background: #F8F9FA;
            height: 12px;
            margin: 0px;
            border-radius: 6px;
            border: 1px solid #E1E4E8;
        }
        QScrollBar:horizontal:hover {
            background: #F1F2F4;
        }
        QScrollBar::handle:horizontal {
            background: #D1D5DB;
            border: 2px solid transparent;
            border-radius: 5px;
            min-width: 20px;
        }
        QScrollBar::handle:horizontal:hover {
            background: #9CA3AF;
            border: 2px solid #D1D5DB;
        }
        QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {
            border: none;
            background: none;
            width: 0px;
        }
        QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {
            background: none;
        }
    )");
}

void CodeEditor::setContextMenuDarkTheme(QMenu* menu)
{
    menu->setStyleSheet(R"(
        QMenu {
            background-color: #2D2D30;
            border: 1px solid #3E3E42;
            padding: 5px;
            color: #E8E8E8;
        }
        QMenu::item {
            background-color: transparent;
            color: #E8E8E8;
            padding: 5px 20px;
        }
        QMenu::item:selected {
            background-color: #3E3E42;
            color: #FFFFFF;
        }
        QMenu::item:disabled {
            color: #7A7A7A;
        }
        QMenu::separator {
            height: 1px;
            background-color: #3E3E42;
            margin: 3px 0px;
        }
    )");
}

void CodeEditor::setContextMenuLightTheme(QMenu* menu)
{
    menu->setStyleSheet(R"(
        QMenu {
            background-color: #FFFFFF;
            border: 1px solid #D1D5DB;
            padding: 5px;
            color: #24292E;
        }
        QMenu::item {
            background-color: transparent;
            color: #24292E;
            padding: 5px 20px;
        }
        QMenu::item:selected {
            background-color: #F0F2F5;
            color: #24292E;
        }
        QMenu::item:disabled {
            color: #9CA3AF;
        }
        QMenu::separator {
            height: 1px;
            background-color: #E1E4E8;
            margin: 3px 0px;
        }
    )");
}

void CodeEditor::loadFontSettings()
{
    QFont savedFont = ConfigManager::instance().getEditorFont(this->font());
    this->setFont(savedFont);

    // 更新行号区域
    updateLineNumberAreaWidth(0);

    qDebug() << "加载字体设置:" << savedFont.family() << "大小:" << savedFont.pointSize();
}

void CodeEditor::resizeEvent(QResizeEvent* e)
{
    QPlainTextEdit::resizeEvent(e);

    QRect cr = contentsRect();
    m_lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
}

void CodeEditor::wheelEvent(QWheelEvent* event)
{
    // 检查是否按下了 Ctrl 键
    if (event->modifiers() & Qt::ControlModifier) {
        // 获取滚轮滚动的角度增量
        int delta = event->angleDelta().y();

        if (delta > 0) {
            // 向上滚动，放大
            zoomIn(3);  // 每次放大3个单位
        }
        else if (delta < 0) {
            // 向下滚动，缩小
            zoomOut(3);  // 每次缩小3个单位
        }

        // 关键修复：缩放后立即更新行号区域，确保行号字体同步
        updateLineNumberAreaWidth(0);
        m_lineNumberArea->update();

        // 阻止事件继续传播
        event->accept();
    }
    else {
        // 没有按 Ctrl 键，执行正常的滚动操作
        QPlainTextEdit::wheelEvent(event);
    }
}

void CodeEditor::contextMenuEvent(QContextMenuEvent* event)
{
    // 1. 获取右键点击位置对应的当前行号（1开始，与编辑器显示一致）
    QTextCursor cursor = cursorForPosition(event->pos()); // 按点击位置定位光标
    int currentLine = cursor.blockNumber() + 1; // blockNumber()返回0开始索引，+1转为1开始行号

    // 2. 创建菜单
    QMenu* customMenu = new QMenu(this);

    // 根据当前主题设置菜单样式
    ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();
    if (currentTheme == ThemeManager::Theme::Dark) {
        setContextMenuDarkTheme(customMenu);
    }
    else {
        setContextMenuLightTheme(customMenu);
    }

    QAction* addTagAction = customMenu->addAction("添加标签");
    QAction* switchFont = customMenu->addAction("切换字体");

    // 3. 绑定点击事件：发射信号并透传当前行号
    connect(addTagAction, &QAction::triggered, this, [=]() {
        emit addLabelClicked(currentLine); // 点击后发射信号，携带当前行号
        });
    connect(switchFont, &QAction::triggered, this, &CodeEditor::onSwitchFontTriggered);

    // 4. 在点击位置显示菜单，完成后释放内存
    customMenu->exec(event->globalPos());
    delete customMenu;
}

void CodeEditor::keyPressEvent(QKeyEvent* event)
{
    // ctrl + f 快捷键触发查找功能
    if (event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_F) {
        // 新建悬浮窗并关联当前Editor
        if (!m_suspendedSearchBox) {
            m_suspendedSearchBox = new SuspendedSearchBox(this, nullptr);
        }
        m_suspendedSearchBox->show();
        return; // 处理完毕，返回
    }
    // 其他按键事件默认处理
    QPlainTextEdit::keyPressEvent(event);
}

void CodeEditor::highlightCurrentLine()
{
    QList<QTextEdit::ExtraSelection> extraSelections;

    if (!isReadOnly()) {
        QTextEdit::ExtraSelection selection;

        // 根据当前主题设置当前行高亮颜色
        ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();
        QColor lineColor;
        if (currentTheme == ThemeManager::Theme::Dark) {
            lineColor = QColor(76, 80, 92); // 深色主题的当前行颜色
        }
        else {
            lineColor = QColor(Qt::yellow).lighter(160); // 浅色主题的当前行颜色
        }

        selection.format.setBackground(lineColor);
        selection.format.setProperty(QTextFormat::FullWidthSelection, true);
        selection.cursor = textCursor();
        selection.cursor.clearSelection();
        extraSelections.append(selection);
    }

    setExtraSelections(extraSelections);
}

void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent* event)
{
    QPainter painter(m_lineNumberArea);

    // 根据当前主题设置行号区域背景色
    ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();
    if (currentTheme == ThemeManager::Theme::Dark) {
        painter.fillRect(event->rect(), QColor(30, 30, 30)); // 深色背景
    }
    else {
        painter.fillRect(event->rect(), QColor(240, 240, 240)); // 浅色背景
    }

    // 关键修复：使用编辑器的字体，确保行号字体与编辑器同步
    painter.setFont(this->font());

    QTextBlock block = firstVisibleBlock();
    int blockNumber = block.blockNumber();
    int top = qRound(blockBoundingGeometry(block).translated(contentOffset()).top());
    int bottom = top + qRound(blockBoundingRect(block).height());

    while (block.isValid() && top <= event->rect().bottom()) {
        if (block.isVisible() && bottom >= event->rect().top()) {
            QString number = QString::number(blockNumber + 1);

            // 根据当前主题设置行号颜色
            if (currentTheme == ThemeManager::Theme::Dark) {
                painter.setPen(QColor(150, 150, 150)); // 深色主题的行号颜色
            }
            else {
                painter.setPen(QColor(120, 120, 120)); // 浅色主题的行号颜色
            }

            // 关键修复：使用块的实际高度，并垂直居中对齐
            int blockHeight = qRound(blockBoundingRect(block).height());
            painter.drawText(0, top, m_lineNumberArea->width() - 3, blockHeight,
                Qt::AlignRight | Qt::AlignVCenter, number);
        }

        block = block.next();
        top = bottom;
        bottom = top + qRound(blockBoundingRect(block).height());
        ++blockNumber;
    }
}